import mongoose, { Schema } from 'mongoose';

const schema = new Schema(
  {
    user: { type: Schema.Types.ObjectId, ref: 'User', index: true },
    channel: { type: Schema.Types.ObjectId, ref: 'Channel', index: true },
    mark: Boolean,
    starredMessages: [{ type: Schema.Types.ObjectId, ref: 'Message' }],
    lastActiveAt: { type: Date, default: Date.now },
    lastMessage: { type: Schema.Types.ObjectId, ref: 'Message' },
    unreadCount: { type: Number },
    mentionCount: { type: Number },
    lastActiveSocialId: { type: String },
  },
  {
    collection: 'channel_users',
  },
);


/**
 * Instance Methods------------------------------------------------
 */
schema.methods.getUnreadCount = async function getUnreadCount() {
  const MessageModel = mongoose.model('Message');

  const unreadCount = await MessageModel.count({
    toChannel: this.channel,
    createdAt: { $gt: this.lastActiveAt },
  });

  return unreadCount;
};

export default mongoose.model('ChannelUser', schema);
